from app.models import User,Student
from app.extensions import db

class UserService:
    """用户管理服务"""

    @staticmethod
    def get_user_profile(user_id: int) -> dict:
        """获取用户详细信息"""
        user = User.query.get(user_id)
        if not user:
            return {'code': 404, 'msg': '用户不存在'}
        return {'code': 200, 'data': user.to_dict()}

    @staticmethod
    def update_user_info(user_id: int, **kwargs) -> dict:
        """更新用户信息"""
        user = User.query.get(user_id)
        if not user:
            return {'code': 404, 'msg': '用户不存在'}
        
        if 'mobile' in kwargs:
            if User.query.filter(User.mobile == kwargs['mobile']).first():
                return {'code': 400, 'msg': '手机号已被使用'}
            user.mobile = kwargs['mobile']
        
        if 'email' in kwargs:
            if User.query.filter(User.email == kwargs['email']).first():
                return {'code': 400, 'msg': '邮箱已被使用'}
            user.email = kwargs['email']
        
        db.session.commit()
        return {'code': 200, 'msg': '信息更新成功'}
    
    @staticmethod
    def get_student_id(user_id: int)->dict:
        """获取学生id"""
        student = Student.query.filter(Student.user_id == user_id).first()
        if not student:
            return {'code': 404, 'msg': '学生不存在'}
        return {'code': 200, 'data': student.to_dict()}